package com.lagou.homework1_4.test01;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

public class StudentManagement {

    private List<Student> list = new LinkedList<>();

    /**
     * 每次退出系统时, 将现有的学生列表写入文件中
     */
    public void saveStudentsToFile() {

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("D:/aaa/student.txt"));
            oos.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 每次启动时, 从缓存文件中读取学生列表
     */
    public void readStudentsFromFile() {

        ObjectInputStream ois = null;
        try {
            File file = new File("D:/aaa/student.txt");
            if (file.exists() && file.isFile()) {
                ois = new ObjectInputStream(new FileInputStream("D:/aaa/student.txt"));
                Object object = ois.readObject();
                list = (LinkedList)object;
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void add(Student student) {
        list.add(student);
    }

    public boolean del(int id) {
        Student student = find(id);
        if (null == student) {
            return false;
        }
        return list.remove(student);
    }

    public Student find(int id) {
        Student student = null;
        for (Student obj:list) {
            if (obj.getId() == id) {
                student = obj;
            }
        }
        return student;
    }

    public List<Student> findByName(String name) {
        List<Student> students = new LinkedList<>();
        int i = 0;
        for (Student obj:list) {
            if (name.equals(obj.getName())) {
                students.add(obj);
            }
        }
        return students;
    }

    public List<Student> findByAge(int age) {

        List<Student> students = new LinkedList<>();
        int i = 0;
        for (Student obj:list) {
            if (age == obj.getAge()) {
                students.add(obj);
            }
        }
        return students;
    }

    public void show() {
        System.out.println(list);
    }
}
